package com.fast.alden.admin.service.impl;

import com.fast.alden.admin.service.MessageCenterService;
import com.fast.alden.admin.service.SysNoticeService;
import com.fast.alden.admin.service.SysUserService;
import com.fast.alden.common.service.impl.BaseEntityServiceImpl;
import com.fast.alden.data.model.SysMessage;
import com.fast.alden.data.model.SysMessageType;
import com.fast.alden.data.model.SysNotice;
import com.fast.alden.data.model.SysUser;
import com.fast.alden.data.repo.SysNoticeRepository;
import jakarta.annotation.Resource;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class SysNoticeServiceImpl extends BaseEntityServiceImpl<SysNotice, SysNoticeRepository> implements SysNoticeService {
    @Resource
    private SysNoticeRepository repository;
    @Resource
    private SysUserService userService;
    @Resource
    private MessageCenterService messageCenterService;

    @Override
    protected Class<SysNotice> getEClass() {
        return SysNotice.class;
    }

    @Override
    protected SysNoticeRepository getRepository() {
        return repository;
    }

    @Override
    public SysNotice create(SysNotice entity) {
        // 新建的通知发布状态为false，发布时间为null
        entity.setPublished(false);
        entity.setPublishedTime(null);
        return super.create(entity);
    }

    @Override
    @Transactional
    public void publish(Long id) {
        SysNotice notice = this.retrieveWithException(id);

        notice.setPublished(true);
        notice.setPublishedTime(LocalDateTime.now());
        super.update(notice);

        // 目前仅支持通知全员
        // todo: 通知指定部门、岗位、用户
        List<SysUser> users = userService.list();

        List<SysMessage> messages = users.stream().map(user -> {
            SysMessage message = new SysMessage();
            message.setType(SysMessageType.NOTICE);
            message.setReceiverId(user.getId());
            message.setReceiverName(user.getNickname());
            message.setSenderName("Fast Alden");
            message.setSentTime(LocalDateTime.now());
            message.setReadState(false);
            message.setReadTime(null);
            message.setTitle(notice.getTitle());
            message.setContent(notice.getContent());

            return message;
        }).toList();

        // 使用虚拟线程，如需使用操作系统线程请改为调用ThreadPoolTaskExecutor.execute方法
        Thread.ofVirtual().start(() -> {
            messageCenterService.sendMessage(messages);
        });
    }
}
